<?php
	require '../../include/library.inc.php';
	require '../../include/admin_login.inc.php';
	
	$team_id = intval($_GET['team_id']);
	$direction_check = intval($_GET['direction']);
	$top = intval($_GET['top']);
	$type = escape($_GET['type']);
	if($team_id && ($direction_check == 1 || $direction_check == -1)) {
  	
		# Get the current order number
		$sql = "SELECT 
				  order_number
				FROM
				  team
				WHERE
				  team_id = ".$team_id."
				";
		$result = query($sql);
		$row = mysql_fetch_assoc($result);
		$old_order_number = $row['order_number'];
		
		# Get the ID of replaced element
		$sql = "SELECT
				   team_id
				FROM
				   team
				WHERE
				   order_number = ".$old_order_number." + (".$_GET['direction'].")
				   AND type = '".$type."'
				 ";
		$result = query($sql);
		$row = mysql_fetch_assoc($result);
		$replaced_team_id = $row['team_id'];
		 
		# Move current element one position
		$sql = "UPDATE 
				   team
				SET
				  order_number = order_number + (".$_GET['direction'].") 
				WHERE
				   team_id = '".$team_id."' 
				   AND type = '".$type."'
				 ";
		query($sql);
		
		# Move replaced element to currect element's place
		# Update order of replaced element
		$sql = "UPDATE 
				   team
				SET
				  order_number = ".$old_order_number." 
				WHERE
				   team_id = '".$replaced_team_id."'
				   AND type = '".$type."'
				 ";
		query($sql);
		
	} elseif ($team_id && $top==1) {
	  
		$sql = "SELECT MAX(order_number) AS max_order_number FROM team WHERE  type = '".$type."'";
		$row = mysql_fetch_assoc(query($sql));
		$max_order_number = $row['max_order_number'];
		  
		$sql = "SELECT
				  order_number
				FROM
				  team
				WHERE
				  team_id = '$team_id'
				  
				  AND type = '".$type."'
				  ";
		query($sql);
		$row = mysql_fetch_assoc(query($sql));
		$order_number = $row['order_number'];
		
		$sql = "UPDATE
				  team
				SET
				  order_number = order_number - 1
				WHERE
				  order_number > '$order_number'
				  
				  AND type = '".$type."'
				  ";
		query($sql);
		
		$sql = "UPDATE
				  team
				SET
				  order_number = $max_order_number
				WHERE
				  team_id = '$team_id'
				  
				  AND type = '".$type."'
				  ";
		query($sql);
	  
	}
  
	redirect($_SERVER['HTTP_REFERER']);
?>